/*
 * The MIT License
 * 
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package hudson.tasks;

import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.EnvVars;
import hudson.logging.HudsonTestLog;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.TaskListener;

import java.io.IOException;
import java.sql.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Common part between {@link Shell} and {@link BatchFile}.
 * 
 * @author Kohsuke Kawaguchi
 */
public abstract class CommandInterpreter extends Builder  {
    /**
     * Command to execute. The format depends on the actual {@link CommandInterpreter} implementation.
     */
    protected final String command;
  
    public CommandInterpreter(String command,String isExecuteCurrent) {
        this.command = command;
        this.isExecuteCurrent = isExecuteCurrent;        
    }

    public final String getCommand() {
        return command;
    }
    
    @Override
    public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException{
        return perform(build,launcher,(TaskListener)listener);
    }

    /**
     *execute the command ,and return the command execute exit code 
     */
    public boolean perform(AbstractBuild<?,?> build, Launcher launcher, TaskListener listener) throws InterruptedException{
//        listener.getLogger().println("**********************step_"+this.getStepsNumber()+" started **********************");
        FilePath ws = build.getWorkspace();
        build.getProject();
        //listener.getLogger().println("CommandInterpreter class : perform mathod : "+ws);
        FilePath script=null;
        try {
            try {
                build.getBuiltOn().getRootPath();
                script = createScriptFile(ws);
            } catch (IOException e) {
                Util.displayIOException(e,listener);
                e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_UnableToProduceScript()));
                return false;
            }

            int r;
            try {
                EnvVars envVars = build.getEnvironment(listener);
                // on Windows environment variables are converted to all upper case,
                // but no such conversions are done on Unix, so to make this cross-platform,
                // convert variables to all upper cases.
                for(Map.Entry<String,String> e : build.getBuildVariables().entrySet()){
                    envVars.put(e.getKey(),e.getValue());
                }                                                                                   
                    
//                Map<String,String> maptem =MysqlDb.getEnvarPass2Proc(build.getJobName(), build.getProject().getLastBuild().getNumber());                                                                                
                //at first we should make the CI_EXITCODE is null
//                maptem.put("CI_EXITCODE","");
                
                //resolve environment variable against each other
//                EnvVars.resolve(maptem);

                //listener.getLogger().println("resolve environment variables is : "+maptem.size());

                //put all the environment variable in to the map
//                for(String tem:maptem.keySet()){
//                    envVars.put(tem, maptem.get(tem));
//                }             
                                                        
                /***
                 *@since 2012/7/12 
                 * add current build a step , put this step's step number to environment
                 */
                envVars.put("STEP_NUMBER",String.valueOf(this.getStepsNumber()));
                
                /**
                 * current build is sequence or is concurrent? 
                 */
                envVars.put("CONCOURRENT_BUILD",build.getProject().getConcurrentBuild()+"");
                
                build.getProject().getToolParents();                                      
               
                Logger.getLogger(CommandInterpreter.class.getName()).log(HudsonTestLog.level," debug trace");
                r = launcher.launch().cmds(buildCommandLine(script)).envs(envVars).stdout(listener).pwd(ws).join();
              
            } catch (IOException e) {
                Util.displayIOException(e,listener);
                e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_CommandFailed()));
                //if you execute linux/unix shell on windows , or run windows bat on linux/unix like platform could throws this exception
//                MysqlDb.insertExceptionLogWithJobnameBuildnum(build.getJobName(), build.getNumber(), e);
                r = -1;
            }
//            listener.getLogger().println("**********************step_"+this.getStepsNumber()+" exit with code "+r+"**********************");
            
            //we should check the user give an exit code for current steps build
//            Integer tem=MysqlDb.getCiExitCodeWithJobnameBuildnumStepnum(build.getJobName(), build.getNumber(),getStepsNumber());
//            if(tem!=null){
//                MysqlDb.updateStepFinished(build.getJobName(), build.getNumber(), getStepsNumber(), tem, build.getCurrentStepLogWithStepnumber(getStepsNumber()));
//                return r==tem;
//            }
                              
            Logger.getLogger(CommandInterpreter.class.getName()).log(HudsonTestLog.level," exit updata log ");
            return r==0;
            
        } finally {
            try {
                if(script!=null)
                script.delete();
            } catch (IOException e) {
                Util.displayIOException(e,listener);
                e.printStackTrace( listener.fatalError(Messages.CommandInterpreter_UnableToDelete(script)) );
            }
        }
    }

    /**
     * Creates a script file in a temporary name in the specified directory.
     */
    public FilePath createScriptFile(FilePath dir) throws IOException, InterruptedException {
        String tem="";
        if(getFileExtension()==".bat" ){
            String bat_tem = getContents();
            bat_tem=bat_tem.replace("\n", "\r\n");
            StringBuffer sb = new StringBuffer(bat_tem);      
            tem=new String(sb);            
        }
        if(getFileExtension()==".sh"){
            StringBuffer sb = new StringBuffer(getContents());            
            sb.append("\nexit $?");
            tem=new String(sb);
        }
        if(getFileExtension()==".py"){
            String str=getContents();
            StringBuffer sb = new StringBuffer(str); 
            tem=new String(sb);
        }
        Logger.getLogger(CommandInterpreter.class.getName()).log(HudsonTestLog.level, "now the build script content is "+tem);
        return dir.createTextTempFile("hudson", getFileExtension(), tem , false);
    }

    public abstract String[] buildCommandLine(FilePath script);

    protected abstract String getContents();

    protected abstract String getFileExtension();
}
